<template>
	<view class="user-info">
		<uni-forms :value="form" ref="form" :border="false" :rules="rules">
			<uni-forms-item name="realName" label="姓名" :required="true">
				<uni-easyinput type="text" :inputBorder="false" v-model="form.realName" placeholder="真实姓名" />
			</uni-forms-item>
			<uni-forms-item name="sex" label="性别" :required="true">
				<view class="form-sex-item">
					<radio-group @change="radioChange">
						<label>
							<radio value="1" checked="true" v-if="form.sex === 1" style="transform:scale(0.7)"
								color="#68bfd6" />
							<radio value="1" v-else-if="form.sex !== 1" style="transform:scale(0.7)" color="#68bfd6" />
							男
						</label>
						<label>
							<radio value="2" checked="true" v-if="form.sex === 2" style="transform:scale(0.7)"
								color="#68bfd6" />
							<radio value="2" v-else-if="form.sex !== 2" style="transform:scale(0.7)" color="#68bfd6" />
							女
						</label>
					</radio-group>
				</view>
			</uni-forms-item>
			<uni-forms-item name="birthDay" label="出生日期" :required="true">
				<uni-datetime-picker type="date" v-model="form.birthDay" return-type="string"
					class="form-birthDay-item"></uni-datetime-picker>
			</uni-forms-item>
			<uni-forms-item name="userExtend.health" label="健康状况" :required="true">
				<uni-easyinput type="text" :inputBorder="false" v-model="form.userExtend.health" placeholder="健康状况" />
			</uni-forms-item>
			<uni-forms-item name="idCard" label="身份证号" :required="true">
				<uni-easyinput type="text" :inputBorder="false" v-model="form.idCard" placeholder="身份证号" />
			</uni-forms-item>
			<uni-forms-item name="phone" label="手机号" :required="true">
				<uni-easyinput type="text" :inputBorder="false" v-model="form.phone" placeholder="手机号" />
			</uni-forms-item>
			<uni-forms-item name="userExtend.workUnitType" label="工种" :required="true">
				<uni-easyinput type="text" :inputBorder="false" v-model="form.userExtend.workUnitType"
					:styles="disable.jobTitle?disableStyle:enableStyle" placeholder="工作单位及职务/工种" />
			</uni-forms-item>

			<uni-forms-item name="userExtend.workTime" label="参加工作时间" :required="true" :labelWidth='200'>
				<uni-datetime-picker type="date" v-model="form.userExtend.workTime" return-type="string"
					class="form-birthDay-item"></uni-datetime-picker>
			</uni-forms-item>
			<uni-forms-item name="userExtend.jobEducationMajor" label="在职教育毕业院校及专业" :required="true" :labelWidth='200'>
				<uni-easyinput type="text" :inputBorder="false" v-model="form.userExtend.jobEducationMajor"
					:styles="disable.jobEducationMajor?disableStyle:enableStyle" placeholder="在职教育毕业院校及专业" />
			</uni-forms-item>
			<uni-forms-item name="userExtend.mailAddressCode" label="通信地址及邮编" :required="true" :labelWidth='200'>
				<uni-easyinput type="text" :inputBorder="false" v-model="form.userExtend.mailAddressCode"
					:styles="disable.mailAddressCode?disableStyle:enableStyle" placeholder="通信地址及邮编" />
			</uni-forms-item>
			<!-- <uni-forms-item name="jobResume" label="工作简介" :required="true" :labelWidth='200'>
				<uni-easyinput type="text" :inputBorder="false" v-model="form.userExtend.jobResume"
					:styles="disable.jobResume?disableStyle:enableStyle" placeholder="工作简介" />
			</uni-forms-item> -->
			<uni-forms-item name="imagePath" v-for="(item,index) in dictData" :label="item.dictLabel" :labelWidth='200'>
				<view class="portrait-box">
					<view class="portraitBox" v-for="(file,idx) in item.fileList" v-if="item.fileList.length>0">
						<image class="portrait" :src="file.fileUrl" @click="chooseImage(item,index,file,idx)"></image>
						<uni-icons class="close" type="clear" size="30"
							@click="delImage(item,index,file,idx)"></uni-icons>
					</view>
					<view class="path" style="text-align: center;line-height: 200rpx" @click="addImage(item,index)">
						<uni-icons type="cloud-upload" color="#999" size="100" style="margin:0 auto"></uni-icons>
					</view>
				</view>
			</uni-forms-item>
		</uni-forms>
		<view class="uni-form-item uni-column">
			<button class="cu-btn block bg-blue margin-tb-sm lg action-button" @click="formSubmit">保存</button>
			<!-- <button class="cu-btn block bg-blue margin-tb-sm lg action-button" @click="formExport">一人一档导出</button> -->
		</view>

	</view>
</template>

<script>
	import userApi from '@/api/user.js'

	export default {
		data() {
			return {
				form: {
					realName: null,
					idCard: null,
					id: null,
					workNo: null,
					jobTitle: null,
					sex: null,
					birthDay: null,
					phone: null,
					createTime: null,
					// imagePath: null,
					health: null,
					path: null,
					userExtend: []
				},
				disable: {
					realName: false,
					idCard: false,
					workNo: false,
					jobTitle: false
				},
				rules: {
					realName: {
						rules: [{
							required: true,
							errorMessage: '请输入真实姓名',
						}]
					},
					sex: {
						rules: [{
							required: true,
							errorMessage: '请选择性别',
						}]
					},
					birthDay: {
						rules: [{
							required: true,
							errorMessage: '请选择出生日期',
						}]
					},
					"userExtend.health": {
						rules: [{
							required: true,
							errorMessage: '请输入健康状况',
						}]
					},
					"userExtend.workUnitType": {
						rules: [{
							required: true,
							errorMessage: '请输入工作单位及职务',
						}]
					},
					"userExtend.jobEducationMajor": {
						rules: [{
							required: true,
							errorMessage: '请输入在职教育毕业院校及专业',
						}]
					},
					"userExtend.workTime": {
						rules: [{
							required: true,
							errorMessage: '请选择参加工作时间',
						}]
					},
					"userExtend.mailAddressCode": {
						rules: [{
							required: true,
							errorMessage: '请输入通信地址及邮编',
						}]
					},
					idCard: {
						rules: [{
							required: true,
							errorMessage: '请输入身份证号',
						}]
					},
					phone: {
						rules: [{
							required: true,
							errorMessage: '请输入手机号',
						}]
					},
					jobTitle: {
						rules: [{
							required: true,
							errorMessage: '请输入工作单位及职务/工种',
						}]
					}
				},
				enableStyle: {
					color: '#333',
					disableColor: '#eee',
					borderColor: '#e5e5e5'
				},
				disableStyle: {
					color: '#9b9b9b',
					disableColor: 'transparent',
				},
				userFileList: [],
				dictData: []
			}
		},
		onLoad() {
			this.load()
			setTimeout(() => {
				this.fileLoad()
			}, 500);
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			disableForm() {
				if (this.form.realName !== null && this.form.realName.length > 0) {
					this.disable.realName = true
				}
				if (this.form.idCard !== null && this.form.idCard.length > 0) {
					this.disable.idCard = true
				}
				if (this.form.workNo !== null && this.form.workNo.length > 0) {
					this.disable.workNo = true
				}
				if (this.form.jobTitle !== null && this.form.jobTitle.length > 0) {
					this.disable.jobTitle = true
				}
			},
			load() {
				userApi.selectList().then(res => {
					console.log(res, '数据')
					this.form = res.response
					this.disableForm()
				}).finally(error => {
					uni.stopPullDownRefresh()
				})
				userApi.getDictDataInfoFun('user_file_type').then(data => {
					console.log(data, '数据啊')
					data.response.forEach(item => {
						item.fileList = []
					})
					this.dictData = data.response
				}).finally(error => {
					uni.stopPullDownRefresh()
				})

			},
			fileLoad() {
				let that = this;
				userApi.getUserFile({
					userId: this.form.id
				}).then(re => {
					this.userFileList = re.response
					this.userFileList.forEach(function(item) {
						that.dictData.forEach(function(items, index) {
							if (item.dictCode == items.dictCode) {
								items.fileList.push({
									...item,
									name: item.fileUrl.split('/')[item.fileUrl.split('/')
										.length - 1],
								});
							}
						});
					});
					console.log(1, that.dictData)
				}).finally(error => {
					uni.stopPullDownRefresh()
				})
				//
				console.log(    this.userFileList)
			},
			onPullDownRefresh() {
				this.load()
			},
			radioChange(e) {
				this.form.sex = e.detail.value
			},
			delImage(item, index, file, idx) {
				userApi.userFileDel({
					ids: [item.fileList[idx].id]
				}).then(res => {
					console.log("删除成功")
					item.fileList.splice(idx, 1)
				})
			},
			addImage(item, index) {
				let that = this
				let fileObj = {
					fileUrl: "",
					fileType: "",
					userId: that.form.id,
					dictCode: item.dictCode,
					fileName: ""
				}
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					success: (res) => {
						console.log(res, '图片')
						const tempFilePath = res.tempFilePaths[0];
						fileObj.fileType = res.tempFiles[0].type
						fileObj.fileName = res.tempFiles[0].name
						let query = {
							path: tempFilePath,
							file: "imageFile"
						}
						userApi.uploadUser(query).then(res => {
							console.log(res, '文件')
							fileObj.fileUrl = res.response
							userApi.userFileAdd(fileObj).then(res => {
								fileObj.id = res.response;
								item.fileList.push(fileObj)
							})
						})
					}
				});
			},
			chooseImage(item, index, file, idx) {
				let that = this
				let fileObj = {
					fileUrl: "",
					fileType: "",
					userId: that.form.id,
					dictCode: item.dictCode,
					fileName: ""
				}
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0];
						fileObj.fileType = res.tempFiles[0].type
						fileObj.fileName = res.tempFiles[0].name
						let query = {
							path: tempFilePath,
							name: "imageFile"
						}
						userApi.uploadUser(query).then(res => {
							console.log("上传回显的数据", res.data[0])
							fileObj.fileUrl = res.data[0].url
							userApi.userFileAdd(fileObj).then(res => {
								fileObj.id = res.response;
								if (item.fileList.length > 0) {
									userApi.userFileDel({
										ids: [item.fileList[idx].id]
									}).then(res => {
										console.log("删除成功")
									})
									item.fileList.splice(idx, 1, fileObj)
								} else {
									item.fileList.push(fileObj)
								}
							})
						})
					}
				});
			},
			formSubmit() {
				this.$refs.form.submit().then(res => {
					this.form.userExtend.workTime = this.form.userExtend.workTime.substring(0, 11)
					this.form.imagePath = "1111"
					userApi.userExtendUpdate(this.form).then(data => {
						if (data.code === 1) {
							uni.showModal({
								title: '提示',
								content: '个人资料修改成功',
								showCancel: false,
								success: function(res) {
									let pages = getCurrentPages()
									if (pages.length >= 2) {
										var prepage = pages[pages.length - 2]
										if (prepage.route === 'pages/my/index') {
											prepage.$vm.load()
										}
										uni.navigateBack()
									}
								}
							});
						} else {
							uni.showToast({
								icon: 'none',
								title: data.message
							});
						}
					})
				}).catch(e => {})
			},
			formExport() {
				userApi.exportYryd(this.form.id).then(res => {
					const currentDate = new Date();
					const year = currentDate.getFullYear();
					const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
					const day = currentDate.getDate().toString().padStart(2, '0');
					const time = year + '年' + month + '月' + day + '日';
					let blob = new Blob([res], {
						type: 'application/zip;charset=utf-8'
					});
					console.log(blob)
					// 创建 href 超链接，点击进行下载
					window.URL = window.URL || window.webkitURL;
					let href = URL.createObjectURL(blob);
					let downA = document.createElement("a");
					downA.href = href;
					downA.download = '一人一档' + '-' + this.form.realName + '-' + time;
					downA.click();
					// 销毁超连接
					window.URL.revokeObjectURL(href);
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #FFFFFF;
	}

	.label-text {
		width: 220px;
		display: block;
	}

	.user-info {
		padding: 20rpx;


		.title {
			padding: 10rpx 24rpx;
		}

		.form-sex-item {
			height: 72rpx;
			line-height: 72rpx !important;
		}

		.form-birthDay-item {
			height: 72rpx;
			line-height: 72rpx !important;
		}

		.path {
			width: 200rpx;
			height: 200rpx;
			border: 1rpx solid #ccc;
		}

		.portrait-box {
			display: flex;
			flex-wrap: wrap;
		}

		.portraitBox {
			width: 200rpx;
			position: relative;
			margin-right: 20rpx;
		}

		.close {
			position: absolute;
			right: 0px;
			top: -20rpx;
		}

		.portrait {
			width: 200rpx;
			height: 200rpx;
			border: 1rpx solid #ccc;
		}
	}
</style>